﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.BusinessFlow;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.NotePrint;
using Kingdee.BOS.Core.Validation;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TZ.PlugIn.FileSrv
{
    [Description("采购订单审核生成PDF后上传契约锁")]
    [Kingdee.BOS.Util.HotUpdate]

    public class PurOrderAuditUploadFile : AbstractOperationServicePlugIn
    {
        private string FormId = "PUR_PurchaseOrder";
        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }

        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);
            foreach (var obj in e.SelectedRows.Select(s => s.DataEntity))
            {
                if (obj == null) { return; }
                try
                {
                    // 安全获取用印方式
                    int yyfs = 0;
                    var yyfsObj = obj["FYYFS"];
                    if (yyfsObj != null)
                    {
                        if (!int.TryParse(yyfsObj.ToString(), out yyfs))
                        {
                            this.OperationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = false,
                                Message = $"用印方式格式错误",
                                MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.FatalError,
                                PKValue = 0,
                            });
                            //AddErrorResult("用印方式格式错误");
                            e.Cancel = true;
                            return;
                        }
                    }

                    // 安全获取是否创建账单
                    bool fisCreateBill = false;
                    var fisCreateBillObj = obj["FisCreateBill"];
                    if (fisCreateBillObj != null)
                    {
                        bool.TryParse(fisCreateBillObj.ToString(), out fisCreateBill);
                    }

                    // 如果未创建账单且用印方式为0，进行验证
                    if (yyfs == 0)
                    {
                        // 安全获取供应商联系信息
                        var providerContactId = obj["ProviderContactId"] as DynamicObject;
                        string providerPhone = string.Empty;

                        if (providerContactId != null)
                        {
                            var mobileObj = providerContactId["Mobile"];
                            if (mobileObj != null)
                            {
                                providerPhone = mobileObj.GetString() ?? string.Empty;
                            }
                        }

                        // 验证联系方式
                        if (string.IsNullOrWhiteSpace(providerPhone) || providerContactId == null)
                        {
                            this.OperationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = false,
                                Message = $"供应商联系方式错误，请输入正确的联系方式后重新提交，或者切换到我方单签",
                                MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.FatalError,
                                PKValue = 0,
                            });
                            //AddErrorResult("供应商联系方式错误，请输入正确的联系方式后重新提交，或者切换到我方单签");
                            e.Cancel = true;
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }

        public override void EndOperationTransaction(Kingdee.BOS.Core.DynamicForm.PlugIn.Args.EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);

            int yyfs = Convert.ToInt32(e.DataEntitys.FirstOrDefault()["FYYFS"]);//用印方式
            if (yyfs == 2) { return; }

            int idx = 1;
            string PKID = "1";
            var sql = "";
            var BillNo = "";
            int ErrFlg = 0;
            try
            {
                foreach (var headBill in e.DataEntitys)
                {
                    if (headBill == null)
                        break;

                    ErrFlg = 0;
                    var ErrMsg = "";
                    var DocumentId = "";//签署文件ID
                    var ContractId = "";//签约文件ID
                    var create = headBill["CreatorId"] as DynamicObject;
                    int CreatorId = create == null ? 0 : Convert.ToInt32(create["id"]);
                    var isPost = true;
                    Common.GetParams(this.Context);
                    PKID = headBill["Id"].ToString();
                    BillNo = headBill["BillNo"].ToString();
                    FormId = this.BusinessInfo.GetForm().Id;
                    DynamicObject Supp = headBill["SupplierId"] as DynamicObject;
                    string supName = Supp == null ? "" : Supp["ShortName"].ToString();//由供应商名称改为简称


                    //获取套打模板
                    sql = string.Format("exec SP_QYS_GetPrintTemplateId {0},'{1}'", PKID, FormId);
                    var dyTemplate = DBUtils.ExecuteDynamicObject(this.Context, sql);
                    if (dyTemplate.Count < 1 || dyTemplate[0]["TemplateId"].ToString() == "")
                    {
                        string sqlerr = string.Format("update T_PUR_POORDER set FQYSMESSAGE = '未获取到套打模板' where FID = {0}", PKID);
                        DBUtils.Execute(this.Context, sqlerr);

                        var error = new ValidationErrorInfo(
                                    "",
                                    PKID,
                                    idx,
                                    0,
                                    "001",
                                    "未获取到套打模板",
                                    "审核：" + BillNo,
                                    ErrorLevel.Error
                            );
                        this.OperationResult.ValidationErrors.Add(error);
                        idx += 1;
                        continue;
                    }
                    Common.POTemplateId = dyTemplate[0]["TemplateId"].ToString();

                    //var FisPushQYS = Convert.ToBoolean(headBill["FisPushQYS"].ToString());
                    //if (!FisPushQYS)//未上传文件，才允许上传
                    //{

                    //}

                    //撤回时删除已经上传的附件
                    var InterId = PKID;
                    var FileName = BillNo + ".PDF";//定义文件名：单据编号为文件名
                    sql = string.Format("SELECT  FID FROM T_BAS_ATTACHMENT WHERE FBILLTYPE = '{0}' AND FINTERID = '{1}' and FATTACHMENTNAME = '{2}'", "PUR_PurchaseOrder", InterId, FileName);
                    var dyExists = DBUtils.ExecuteDynamicObject(this.Context, sql);
                    var delAttchmentIds = new List<string>();
                    if (dyExists.Count > 0)
                    {
                        foreach (var dye in dyExists)
                        {
                            delAttchmentIds.Add(dye["FID"].ToString());//构建需要删除的FID集合 
                        }
                    }
                    if (delAttchmentIds.Count > 0)
                    {
                        FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, "BOS_Attachment");

                        DynamicObjectType wlType = meta.BusinessInfo.GetDynamicObjectType();

                        BusinessDataServiceHelper.Delete(this.Context, delAttchmentIds.ToArray(), meta.BusinessInfo.GetDynamicObjectType());
                    }

                    //生成PDF文件
                    var exportFileInfo = Common.GetExportFile(this.Context, FormId, PKID, Common.POTemplateId);

                    var result1 = Common.PostFile(Common.UploadFileUrl, Common.AppToken, Common.AppSecret, exportFileInfo.FilePath, BillNo,supName, ref isPost);
                    if (!isPost)
                    {
                        ErrMsg = result1.ToString().Trim();
                        string sqlerr = string.Format("update T_PUR_POORDER set FQYSMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                        DBUtils.Execute(this.Context, sqlerr);

                        var error = new ValidationErrorInfo(
                                    "",
                                    PKID,
                                    idx,
                                    0,
                                    "001",
                                    "上传文件到契约锁失败：" + ErrMsg,
                                    "审核：" + BillNo,
                                    ErrorLevel.Error
                            );
                        this.OperationResult.ValidationErrors.Add(error);
                        idx += 1;
                        continue;
                    }
                    else
                    {
                        var JsonResult = result1 as JObject;
                        if (JsonResult["code"].ToString() != "0")
                        {
                            ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                            string sqlerr = string.Format("update T_PUR_POORDER set FQYSMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                            DBUtils.Execute(this.Context, sqlerr);

                            var error = new ValidationErrorInfo(
                                "",
                                PKID,
                                idx,
                                0,
                                "001",
                                "上传文件到契约锁失败：" + ErrMsg,
                                "审核：" + BillNo,
                                ErrorLevel.Error
                            );
                            this.OperationResult.ValidationErrors.Add(error);
                            idx += 1;
                            continue;
                        }
                        else
                        {
                            DocumentId = JsonResult["result"]["documentId"].ToString();
                            sql = string.Format("update T_PUR_POORDER set FISPUSHQYS = 1,FQYSMESSAGE = '上传成功', FDOCUMENTID = '{1}' where FID = {0}", PKID, DocumentId);
                            DBUtils.Execute(this.Context, sql);
                        }
                    }

                    ErrFlg = 1;//上传文件没有异常

                    var FisCreateBill = Convert.ToBoolean(headBill["FisCreateBill"].ToString());
                    if (!FisCreateBill)//未创建电子签约单
                    {
                        if (DocumentId == "")
                        {
                            DocumentId = headBill["FDocumentId"].ToString().Trim();
                        }
                        if (DocumentId == "")
                        {
                            sql = string.Format(@"/*dialect*/select top 1 FDOCUMENTID from T_PUR_POORDER where FID = {0}", PKID);
                            var dycollCon = DBUtils.ExecuteDynamicObject(this.Context, sql);
                            if (dycollCon.Count > 0)
                                DocumentId = dycollCon[0]["FDOCUMENTID"].ToString();
                        }
                        if (DocumentId == "")
                        {
                            idx += 1;
                            continue;
                        }

                        sql = string.Format("exec SP_QYS_GetJsonPurOrder {0},{1}", PKID, DocumentId);
                        var dycoll = DBUtils.ExecuteDynamicObject(this.Context, sql);
                        object JsonData = null;
                        if (yyfs == 0)
                        {
                            var ProviderContactId = headBill["ProviderContactId"] as DynamicObject;
                            var ProviderPhone = ProviderContactId["Mobile"] == null ? "" : ProviderContactId["Mobile"].GetString();
                            var Contact = ProviderContactId["Contact"] == null ? "" : ProviderContactId["Contact"].GetString();
                            var FEMail = headBill["F_RNFK_ProviderEMail"] == null ? "" : headBill["F_RNFK_ProviderEMail"].GetString();
                            var FEMai2 = headBill["F_RNFK_PROVIDEREMAIL_Q8S"] == null ? "" : headBill["F_RNFK_PROVIDEREMAIL_Q8S"].GetString();

                            if (ProviderPhone.IsNullOrEmptyOrWhiteSpace() || ProviderContactId.IsNullOrEmptyOrWhiteSpace())
                            {
                                var error = new ValidationErrorInfo(
                                    "",
                                    PKID,
                                    idx,
                                    0,
                                    "001",
                                    $"供应商联系方式错误，请输入正确的联系方式后重新提交，或者切换到我方单签",
                                    "审核：" + BillNo,
                                    ErrorLevel.Error
                                );
                                this.OperationResult.ValidationErrors.Add(error);
                                // 手动回滚
                                RollbackData(new OperationRollbackDataArgs(e.DataEntitys));
                                throw new KDException("102", $"供应商联系方式错误，请输入正确的联系方式后重新提交，或者切换到我方单签");
                                //return;
                            }

                            DynamicObjectCollection mailList = GetMailist(CreatorId);
                            JsonData = Common.GetPurJsonData(this.Context, dycoll, ProviderPhone, PKID, mailList, Contact, FEMail, FEMai2, BillNo, supName);
                        }
                        if (yyfs == 1)
                        {
                            DynamicObjectCollection mailList = GetMailist(CreatorId);
                            var ProviderContactId = headBill["ProviderContactId"] as DynamicObject;
                            var ProviderPhone = ProviderContactId["Mobile"] == null ? "" : ProviderContactId["Mobile"].GetString();
                            var Contact = ProviderContactId["Contact"] == null ? "" : ProviderContactId["Contact"].GetString();
                            var FEMail = headBill["F_RNFK_ProviderEMail"] == null ? "" : headBill["F_RNFK_ProviderEMail"].GetString();
                            var FEMai2 = headBill["F_RNFK_PROVIDEREMAIL_Q8S"] == null ? "" : headBill["F_RNFK_PROVIDEREMAIL_Q8S"].GetString();
                            JsonData = Common.GetPurJsonData1(this.Context, dycoll, PKID, mailList, FEMail, FEMai2, Contact, BillNo,supName);
                        }
                        isPost = true;
                        var result = Common.PostBill(Common.CreateBillUrl, Common.AppToken, Common.AppSecret, JsonData, ref isPost);
                        if (!isPost)
                        {
                            ErrMsg = result.ToString().Trim();
                            string sqlerr = string.Format("update T_PUR_POORDER set FCRTMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                            DBUtils.Execute(this.Context, sqlerr);

                            var error = new ValidationErrorInfo(
                                        "",
                                        PKID,
                                        idx,
                                        0,
                                        "001",
                                        "创建电子签约到契约锁失败：" + ErrMsg,
                                        "审核：" + BillNo,
                                        ErrorLevel.Error
                                );
                            this.OperationResult.ValidationErrors.Add(error);
                            idx += 1;
                            continue;
                        }
                        else
                        {
                            var JsonResult = result as JObject;
                            if (JsonResult["code"].ToString() != "0")
                            {
                                ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                                string sqlerr = string.Format("update T_PUR_POORDER set FCRTMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                                DBUtils.Execute(this.Context, sqlerr);

                                var error = new ValidationErrorInfo(
                                    "",
                                    PKID,
                                    idx,
                                    0,
                                    "001",
                                    "创建电子签约到契约锁失败：" + ErrMsg,
                                    "审核：" + BillNo,
                                    ErrorLevel.Error
                                );
                                this.OperationResult.ValidationErrors.Add(error);
                                idx += 1;
                                continue;
                            }
                            else
                            {
                                ContractId = JsonResult["contractId"].ToString();
                                sql = string.Format("update T_PUR_POORDER set FISCREATEBILL = 1,FCRTMESSAGE = '创建成功',FCONTRACTID = '{1}' where FID = {0}", PKID, ContractId);
                                DBUtils.Execute(this.Context, sql);
                            }
                        }
                    }
                    else
                    {
                        //如果创建过电子签，撤回或者作废合同后需要重新触发创建电子签
                        //作废
                        var FisCancelBill = Convert.ToBoolean(headBill["FisCancelBill"].ToString());
                        //撤回
                        var FisRecallBill = Convert.ToBoolean(headBill["FisRecallBill"].ToString());
                        if (FisCancelBill || FisRecallBill)
                        {
                            //11-02添加的代码段
                            var result2 = Common.PostFile(Common.UploadFileUrl, Common.AppToken, Common.AppSecret, exportFileInfo.FilePath, BillNo, supName, ref isPost);
                            if (!isPost)
                            {
                                ErrMsg = result2.ToString().Trim();
                                string sqlerr = string.Format("update T_PUR_POORDER set FQYSMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                                DBUtils.Execute(this.Context, sqlerr);

                                var error = new ValidationErrorInfo(
                                            "",
                                            PKID,
                                            idx,
                                            0,
                                            "001",
                                            "上传文件到契约锁失败：" + ErrMsg,
                                            "审核：" + BillNo,
                                            ErrorLevel.Error
                                    );
                                this.OperationResult.ValidationErrors.Add(error);
                                idx += 1;
                                continue;
                            }
                            else
                            {
                                var JsonResult = result2 as JObject;
                                if (JsonResult["code"].ToString() != "0")
                                {
                                    ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                                    string sqlerr = string.Format("update T_PUR_POORDER set FQYSMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                                    DBUtils.Execute(this.Context, sqlerr);

                                    var error = new ValidationErrorInfo(
                                        "",
                                        PKID,
                                        idx,
                                        0,
                                        "001",
                                        "上传文件到契约锁失败：" + ErrMsg,
                                        "审核：" + BillNo,
                                        ErrorLevel.Error
                                    );
                                    this.OperationResult.ValidationErrors.Add(error);
                                    idx += 1;
                                    continue;
                                }
                                else
                                {
                                    DocumentId = JsonResult["result"]["documentId"].ToString();
                                    sql = string.Format("update T_PUR_POORDER set FISPUSHQYS = 1,FQYSMESSAGE = '上传成功', FDOCUMENTID = '{1}' where FID = {0}", PKID, DocumentId);
                                    DBUtils.Execute(this.Context, sql);
                                }
                            }

                            ErrFlg = 1;//上传文件没有异常

                            if (DocumentId == "")
                            {
                                DocumentId = headBill["FDocumentId"].ToString().Trim();
                            }
                            if (DocumentId == "")
                            {
                                sql = string.Format(@"/*dialect*/select top 1 FDOCUMENTID from T_PUR_POORDER where FID = {0}", PKID);
                                var dycollCon = DBUtils.ExecuteDynamicObject(this.Context, sql);
                                if (dycollCon.Count > 0)
                                    DocumentId = dycollCon[0]["FDOCUMENTID"].ToString();
                            }
                            if (DocumentId == "")
                            {
                                idx += 1;
                                continue;
                            }

                            sql = string.Format("exec SP_QYS_GetJsonPurOrder {0},{1}", PKID, DocumentId);
                            var dycoll = DBUtils.ExecuteDynamicObject(this.Context, sql);
                            object JsonData = null;
                            if (yyfs == 0)
                            {
                                var ProviderContactId = headBill["ProviderContactId"] as DynamicObject;
                                var ProviderPhone = ProviderContactId["Mobile"] == null ? "" : ProviderContactId["Mobile"].GetString();
                                var Contact = ProviderContactId["Contact"] == null ? "" : ProviderContactId["Contact"].GetString();
                                var FEMail = headBill["F_RNFK_ProviderEMail"] == null ? "" : headBill["F_RNFK_ProviderEMail"].GetString();
                                var FEMai2 = headBill["F_RNFK_PROVIDEREMAIL_Q8S"] == null ? "" : headBill["F_RNFK_PROVIDEREMAIL_Q8S"].GetString();

                                if (ProviderPhone.IsNullOrEmptyOrWhiteSpace() || ProviderContactId.IsNullOrEmptyOrWhiteSpace())
                                {
                                    var error = new ValidationErrorInfo(
                                        "",
                                        PKID,
                                        idx,
                                        0,
                                        "001",
                                        $"供应商联系方式错误，请输入正确的联系方式后重新提交，或者切换到我方单签",
                                        "审核：" + BillNo,
                                        ErrorLevel.Error
                                    );
                                    this.OperationResult.ValidationErrors.Add(error);
                                    // 手动回滚
                                    RollbackData(new OperationRollbackDataArgs(e.DataEntitys));
                                    throw new KDException("101", $"供应商联系方式错误，请输入正确的联系方式后重新提交，或者切换到我方单签");
                                    //return;
                                }
                                DynamicObjectCollection mailList = GetMailist(CreatorId);
                                JsonData = Common.GetPurJsonData(this.Context, dycoll, ProviderPhone, PKID, mailList, Contact, FEMail, FEMai2, BillNo, supName);
                            }
                            if (yyfs == 1)
                            {
                                DynamicObjectCollection mailList = GetMailist(CreatorId);
                                var ProviderContactId = headBill["ProviderContactId"] as DynamicObject;
                                var ProviderPhone = ProviderContactId["Mobile"] == null ? "" : ProviderContactId["Mobile"].GetString();
                                var Contact = ProviderContactId["Contact"] == null ? "" : ProviderContactId["Contact"].GetString();
                                var FEMail = headBill["F_RNFK_ProviderEMail"] == null ? "" : headBill["F_RNFK_ProviderEMail"].GetString();
                                var FEMai2 = headBill["F_RNFK_PROVIDEREMAIL_Q8S"] == null ? "" : headBill["F_RNFK_PROVIDEREMAIL_Q8S"].GetString();
                                JsonData = Common.GetPurJsonData1(this.Context, dycoll, PKID, mailList, FEMail, FEMai2, Contact, BillNo, supName);
                            }
                            isPost = true;
                            var result = Common.PostBill(Common.CreateBillUrl, Common.AppToken, Common.AppSecret, JsonData, ref isPost);
                            if (!isPost)
                            {
                                ErrMsg = result.ToString().Trim();
                                string sqlerr = string.Format("update T_PUR_POORDER set FCRTMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                                DBUtils.Execute(this.Context, sqlerr);

                                var error = new ValidationErrorInfo(
                                            "",
                                            PKID,
                                            idx,
                                            0,
                                            "001",
                                            "创建电子签约到契约锁失败：" + ErrMsg,
                                            "审核：" + BillNo,
                                            ErrorLevel.Error
                                    );
                                this.OperationResult.ValidationErrors.Add(error);
                                idx += 1;
                                continue;
                            }
                            else
                            {
                                var JsonResult = result as JObject;
                                if (JsonResult["code"].ToString() != "0")
                                {
                                    ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                                    string sqlerr = string.Format("update T_PUR_POORDER set FCRTMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                                    DBUtils.Execute(this.Context, sqlerr);

                                    var error = new ValidationErrorInfo(
                                        "",
                                        PKID,
                                        idx,
                                        0,
                                        "001",
                                        "创建电子签约到契约锁失败：" + ErrMsg,
                                        "审核：" + BillNo,
                                        ErrorLevel.Error
                                    );
                                    this.OperationResult.ValidationErrors.Add(error);
                                    idx += 1;
                                    continue;
                                }
                                else
                                {
                                    ContractId = JsonResult["contractId"].ToString();
                                    sql = string.Format("update T_PUR_POORDER set FISCREATEBILL = 1,FCRTMESSAGE = '创建成功',FCONTRACTID = '{1}' where FID = {0}", PKID, ContractId);
                                    DBUtils.Execute(this.Context, sql);
                                }
                            }
                        }
                    }
                    ErrFlg = 2;

                    //印章静默签署
                    Common.SignByCompany = "1";
                    if (Common.SignByCompany == "1")
                    {
                        if (ContractId == "")
                        {
                            ContractId = headBill["FContractId"].ToString().Trim();
                        }
                        if (ContractId == "")
                        {
                            sql = string.Format(@"/*dialect*/select top 1 FCONTRACTID from T_PUR_POORDER where FID = {0}", PKID);
                            var dycollCon = DBUtils.ExecuteDynamicObject(this.Context, sql);
                            if (dycollCon.Count > 0)
                                ContractId = dycollCon[0]["FCONTRACTID"].ToString();
                        }
                        if (ContractId == "")
                        {
                            idx += 1;
                            continue;
                        }

                        //var FisDefSign = Convert.ToBoolean(headBill["FisDefSign"].ToString());
                        //if (FisDefSign)
                        //{
                        //    idx += 1;
                        //    continue;
                        //}

                        sql = string.Format("exec SP_QYS_GetJsonPurOrderDefSign {0},{1},'{2}'", PKID, ContractId, this.Context.UserName);
                        var dycollJson = DBUtils.ExecuteDynamicObject(this.Context, sql);
                        if (dycollJson.Count < 1)
                        {
                            idx += 1;
                            continue;
                        }
                        var JsonData = JObject.Parse(dycollJson[0][0].ToString());
                        isPost = true;
                        var result = Common.PostBill(Common.SignByCpyUrl, Common.AppToken, Common.AppSecret, JsonData, ref isPost);
                        if (!isPost)
                        {
                            ErrMsg = result.ToString().Trim();
                            string sqlerr = string.Format("update T_PUR_POORDER set FDEFMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                            DBUtils.Execute(this.Context, sqlerr);

                            var error = new ValidationErrorInfo(
                                        "",
                                        PKID,
                                        idx,
                                        0,
                                        "001",
                                        "印章静默签署到契约锁失败：" + ErrMsg,
                                        "审核：" + BillNo,
                                        ErrorLevel.Error
                                );
                            this.OperationResult.ValidationErrors.Add(error);
                            idx += 1;
                            continue;
                        }
                        else
                        {
                            var JsonResult = result as JObject;
                            if (JsonResult["code"].ToString() != "0")
                            {
                                ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                                string sqlerr = string.Format("update T_PUR_POORDER set FDEFMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                                DBUtils.Execute(this.Context, sqlerr);

                                var error = new ValidationErrorInfo(
                                    "",
                                    PKID,
                                    idx,
                                    0,
                                    "001",
                                    "印章静默签署到契约锁失败：" + ErrMsg,
                                    "审核：" + BillNo,
                                    ErrorLevel.Error
                                );
                                this.OperationResult.ValidationErrors.Add(error);
                                idx += 1;
                                continue;
                            }
                            else
                            {
                                sql = string.Format("update T_PUR_POORDER set FISDEFSIGN = 1,FDEFMESSAGE = '静默签署成功' where FID = {0}", PKID);
                                DBUtils.Execute(this.Context, sql);
                            }
                        }
                    }
                    ErrFlg = 3;
                    idx += 1;
                }
            }
            catch (Exception ex)
            {
                var error = new ValidationErrorInfo(
                                "",
                                PKID,
                                idx,
                                0,
                                "001",
                                "上传采购订单到契约锁异常：" + ex.Message,
                                "审核:" + BillNo,
                                ErrorLevel.Error
                        );
                this.OperationResult.ValidationErrors.Add(error);

                if (PKID != "1")
                {
                    if (ErrFlg < 1)
                    {
                        sql = string.Format("update T_PUR_POORDER set FQYSMESSAGE = '" + ex.Message.Replace("'", "''") + "' where FID = {0}", PKID);
                        DBUtils.Execute(this.Context, sql);
                    }
                    else if (ErrFlg < 2)
                    {
                        sql = string.Format("update T_PUR_POORDER set FCRTMESSAGE = '" + ex.Message.Replace("'", "''") + "' where FID = {0}", PKID);
                        DBUtils.Execute(this.Context, sql);
                    }
                    else
                    {
                        sql = string.Format("update T_PUR_POORDER set FDEFMESSAGE = '" + ex.Message.Replace("'", "''") + "' where FID = {0}", PKID);
                        DBUtils.Execute(this.Context, sql);
                    }
                }
            }
        }

        private DynamicObjectCollection GetMailist(int creatorId)
        {
            string sql = string.Format(@"/*dialect*/ 
            select FNAME,FEMAIL from T_SEC_user where FUSERID={0} ", creatorId);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }
    }
}
